package com.ipc.admin.service.zzcool.impl;

import cn.hutool.core.lang.UUID;
import com.ipc.admin.service.zzcool.service.CouponDetailsService;
import com.ipc.admin.service.zzcool.service.CouponService;
import com.ipc.common.pojo.vo.R;
import com.ipc.core.dao.zzcool.CouponDao;
import com.ipc.core.entity.zzcool.Coupon;
import com.ipc.core.entity.zzcool.CouponDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author Zzcool
 * @create 2023-04-30 19:13
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Resource
    private CouponDao dao;

    @Resource
    private CouponDetailsService service;

    /**
     * 新增优惠卷
     *
     * @param coupon 优惠卷字段信息
     * @return 成功或失败
     */
    @Override
    public R save(Coupon coupon) {
        if (coupon != null) {
            if (dao.insert(coupon) > 0) {
                return R.ok("添加成功");
            }
        }
        return R.fail("添加失败");
    }

    /**
     * 发放优惠卷
     *
     * @param coupon 优惠卷字段信息
     * @return 成功或失败
     */
    @Override
    public R giveOut(Coupon coupon) {
        if (coupon != null) {
            Integer id = coupon.getId();
            Coupon coupon1 = dao.selectById(id);
            int i1 = dao.updateById(coupon1);
            if (i1 > 0) {
                int i = Integer.parseInt(coupon.getNumber());
                for (int j = 0; j < i; j++) {
                    String replace = UUID.randomUUID().toString().replace("-", "");
                    CouponDetails couponDetails = new CouponDetails(coupon.getId(), replace, "0", "0", "0");
                    service.save(couponDetails);
                }
                return R.ok("添加成功");
            }
        }
        return R.fail("添加失败");
    }


    /**
     * 修改优惠卷
     *
     * @param coupon 优惠卷
     * @return 成功失败
     */
    @Override
    public R updateById(Coupon coupon) {
        if (coupon != null) {
            if (dao.updateById(coupon) > 0) {
                return R.ok("修改成功");
            }
        }
        return R.fail("修改失败");
    }

    /**
     * 删除优惠卷以及发放优惠卷项
     *
     * @param id 优惠卷id
     * @return 成功失败
     */
    @Override
    public R del(int id) {
        if (id > 0) {
            int i = dao.deleteById(id);
            R r = service.delBycid(id);
            int code = r.getCode();
            if (i > 0 && code == 0) {
                return R.ok("删除成功");
            }
        }
        return R.fail("删除失败");
    }

    /**
     * 查询优惠卷项
     *
     * @return 查询成功或失败
     */
    @Override
    public R selectAll() {
        List<Coupon> coupons = dao.selectList(null);
        return R.ok(coupons);
    }
}
